import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Box,
  Card,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Button,
  IconButton,
  Chip,
  Typography,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  FormControlLabel,
  Radio,
  RadioGroup,
  Alert,
  Snackbar,
  Breadcrumbs,
  Link,
} from '@mui/material';
import { Iconify } from 'src/components/iconify';
import { DashboardContent } from 'src/layouts/dashboard';
import { 
  getDictDataByTypeId, 
  saveDictData, 
  updateDictData, 
  deleteDictData, 
  DictData 
} from 'src/api/dict-api';

interface DictDataViewProps {
  typeId: string | null;
  typeName: string | null;
}

export function DictDataView({ typeId, typeName }: DictDataViewProps) {
  const navigate = useNavigate();
  const [dictData, setDictData] = useState<DictData[]>([]);
  const [loading, setLoading] = useState(false);
  const [openDialog, setOpenDialog] = useState(false);
  const [editingData, setEditingData] = useState<DictData | null>(null);
  const [snackbar, setSnackbar] = useState({ open: false, message: '', severity: 'success' as 'success' | 'error' });

  // 表单状态
  const [formData, setFormData] = useState<DictData>({
    typeId: '',
    name: '',
    code: '',
    value: '',
    enabled: 0, // 0表示启用，1表示不启用
    sort: 0,
    icon: '',
    color: '#1976d2',
    description: '',
  });

  // 加载字典数据
  const loadDictData = async () => {
    if (!typeId) return;
    
    setLoading(true);
    try {
      const response = await getDictDataByTypeId(typeId);
      if (response.success) {
        setDictData(response.data || []);
      } else {
        showSnackbar('加载字典数据失败', 'error');
      }
    } catch (error) {
      showSnackbar('加载字典数据失败', 'error');
    } finally {
      setLoading(false);
    }
  };

  // 显示消息提示
  const showSnackbar = (message: string, severity: 'success' | 'error') => {
    setSnackbar({ open: true, message, severity });
  };

  // 打开新增对话框
  const handleAdd = () => {
    setEditingData(null);
    setFormData({
      typeId: typeId || '',
      name: '',
      code: '',
      value: '',
      enabled: 0, // 0表示启用，1表示不启用
      sort: 0,
      icon: '',
      color: '#1976d2',
      description: '',
    });
    setOpenDialog(true);
  };

  // 打开编辑对话框
  const handleEdit = (data: DictData) => {
    setEditingData(data);
    setFormData({
      typeId: data.typeId,
      name: data.name,
      code: data.code,
      value: data.value,
      enabled: data.enabled === 0 ? 0 : 1, // 0表示启用，1表示不启用
      sort: data.sort || 0,
      icon: data.icon || '',
      color: data.color || '#1976d2',
      description: data.description || '',
    });
    setOpenDialog(true);
  };

  // 删除字典数据
  const handleDelete = async (id: string) => {
    if (!id) return;
    
    try {
      const response = await deleteDictData(id);
      if (response.success) {
        showSnackbar('删除成功', 'success');
        loadDictData();
      } else {
        showSnackbar('删除失败', 'error');
      }
    } catch (error) {
      showSnackbar('删除失败', 'error');
    }
  };

  // 保存字典数据
  const handleSave = async () => {
    try {
      const response = editingData
        ? await updateDictData({ ...formData, id: editingData.id })
        : await saveDictData(formData);
      
      if (response.success) {
        showSnackbar(editingData ? '更新成功' : '保存成功', 'success');
        setOpenDialog(false);
        loadDictData();
      } else {
        showSnackbar(editingData ? '更新失败' : '保存失败', 'error');
      }
    } catch (error) {
      showSnackbar(editingData ? '更新失败' : '保存失败', 'error');
    }
  };

  // 返回字典类型管理
  const handleBack = () => {
    navigate('/dict-management');
  };

  // 初始化加载
  useEffect(() => {
    if (typeId) {
      loadDictData();
    }
  }, [typeId]);

  if (!typeId) {
    return (
      <DashboardContent>
        <Typography variant="h6" color="error">
          缺少字典类型ID参数
        </Typography>
        <Button onClick={handleBack} sx={{ mt: 2 }}>
          返回字典管理
        </Button>
      </DashboardContent>
    );
  }

  return (
    <DashboardContent>
      {/* 面包屑导航 */}
      <Breadcrumbs sx={{ mb: 3 }}>
        <Link
          component="button"
          variant="body1"
          onClick={handleBack}
          sx={{ cursor: 'pointer' }}
        >
          字典管理
        </Link>
        <Typography color="text.primary">{typeName || '字典数据'}</Typography>
      </Breadcrumbs>

      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
        <Typography variant="h5">
          {typeName} - 字典数据管理
        </Typography>
        <Button
          variant="contained"
          startIcon={<Iconify icon="eva:plus-fill" />}
          onClick={handleAdd}
        >
          新增数据
        </Button>
      </Box>

      <Card>
        <TableContainer component={Paper}>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell>名称</TableCell>
                <TableCell>编码</TableCell>
                <TableCell>值</TableCell>
                <TableCell>描述</TableCell>
                <TableCell>状态</TableCell>
                <TableCell>排序</TableCell>
                <TableCell>图标</TableCell>
                <TableCell>颜色</TableCell>
                <TableCell>创建时间</TableCell>
                <TableCell>操作</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {dictData.map((data) => (
                <TableRow key={data.id}>
                  <TableCell>{data.name}</TableCell>
                  <TableCell>{data.code}</TableCell>
                  <TableCell>{data.value}</TableCell>
                  <TableCell>{data.description}</TableCell>
                  <TableCell>
                    <Chip
                      label={data.enabled === 0 ? '启用' : '禁用'}
                      color={data.enabled === 0 ? 'success' : 'default'}
                      size="small"
                    />
                  </TableCell>
                  <TableCell>{data.sort}</TableCell>
                  <TableCell>{data.icon}</TableCell>
                  <TableCell>
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                      <Box
                        sx={{
                          width: 20,
                          height: 20,
                          borderRadius: '50%',
                          backgroundColor: data.color,
                        }}
                      />
                      {data.color}
                    </Box>
                  </TableCell>
                  <TableCell>{data.createDate}</TableCell>
                  <TableCell>
                    <IconButton onClick={() => handleEdit(data)} color="primary" title="编辑">
                      <Iconify icon="eva:edit-fill" />
                    </IconButton>
                    <IconButton onClick={() => handleDelete(data.id!)} color="error" title="删除">
                      <Iconify icon="eva:trash-2-fill" />
                    </IconButton>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
      </Card>

      {/* 新增/编辑对话框 */}
      <Dialog open={openDialog} onClose={() => setOpenDialog(false)} maxWidth="md" fullWidth>
        <DialogTitle>{editingData ? '编辑字典数据' : '新增字典数据'}</DialogTitle>
        <DialogContent>
          <Box sx={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 2, mt: 2 }}>
            <TextField
              label="名称"
              value={formData.name}
              onChange={(e) => setFormData({ ...formData, name: e.target.value })}
              fullWidth
              required
            />
            <TextField
              label="编码"
              value={formData.code}
              onChange={(e) => setFormData({ ...formData, code: e.target.value })}
              fullWidth
              required
            />
            <TextField
              label="值"
              value={formData.value}
              onChange={(e) => setFormData({ ...formData, value: e.target.value })}
              fullWidth
              required
            />
            <TextField
              label="排序"
              type="number"
              value={formData.sort}
              onChange={(e) => setFormData({ ...formData, sort: parseInt(e.target.value) || 0 })}
              fullWidth
            />
            <TextField
              label="图标"
              value={formData.icon}
              onChange={(e) => setFormData({ ...formData, icon: e.target.value })}
              fullWidth
            />
            <TextField
              label="颜色"
              value={formData.color}
              onChange={(e) => setFormData({ ...formData, color: e.target.value })}
              fullWidth
            />
            <TextField
              label="描述"
              value={formData.description}
              onChange={(e) => setFormData({ ...formData, description: e.target.value })}
              fullWidth
              multiline
              rows={2}
            />
            <RadioGroup
              value={formData.enabled}
              onChange={(e) => setFormData({ ...formData, enabled: parseInt(e.target.value) })}
              row
            >
              <FormControlLabel value={0} control={<Radio />} label="启用" />
              <FormControlLabel value={1} control={<Radio />} label="禁用" />
            </RadioGroup>
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setOpenDialog(false)}>取消</Button>
          <Button onClick={handleSave} variant="contained">
            {editingData ? '更新' : '保存'}
          </Button>
        </DialogActions>
      </Dialog>

      {/* 消息提示 */}
      <Snackbar
        open={snackbar.open}
        autoHideDuration={6000}
        onClose={() => setSnackbar({ ...snackbar, open: false })}
      >
        <Alert severity={snackbar.severity} onClose={() => setSnackbar({ ...snackbar, open: false })}>
          {snackbar.message}
                 </Alert>
       </Snackbar>
     </DashboardContent>
   );
 }
